package com.dtjd.playcoinmonkey.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.adapter.HomeListAdapter;
import com.dtjd.playcoinmonkey.bean.HomeListBean;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.ActivityMyPostBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MyPostActivity extends AppCompatActivity {
    private final List<HomeListBean> data=new ArrayList<>();
    private HomeListAdapter adp;
    private int current=1;
    private int nowPos=0;
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){ finish(); }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMyPostBinding binding = ActivityMyPostBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setTitle(getResources().getString(R.string.myposts));
        ActionBar actionbar = getSupportActionBar();
        if (actionbar!=null){
            actionbar.setDisplayHomeAsUpEnabled(true);
            actionbar.setHomeButtonEnabled(true);
        }
        adp=new HomeListAdapter(this, data, (v, position) -> {
            Tools.showDialog(MyPostActivity.this, getResources().getString(R.string.tips),
                    getResources().getString(R.string.deletePostConfirm),
                    getResources().getString(R.string.confirm),
                    (o, dialog) -> { dialog.dismiss();
                        HomeListBean bean = data.get(position);
                        List<HttpParaBean> para = new ArrayList<>();
                        para.add(new HttpParaBean("token", "token"));
                        para.add(new HttpParaBean("id", bean.id));
                        Network.post(para, "wbhMain/deletePost", new Callback() {
                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                e.printStackTrace();
                            }
                            @Override
                            public void onResponse(@NonNull Call call, @NonNull Response response) {
                                runOnUiThread(() -> {
                                    try {
                                        Tools.toast( new JSONObject(Objects.requireNonNull(response.body()).string()).getString("datalist"));
                                    } catch (Exception  e) {
                                        e.printStackTrace();
                                    }
                                    refresh(null, null);
                                });

                            }
                        });
                    }, getResources().getString(R.string.cancel), (o, dialog) -> dialog.dismiss());
        }, (v, position) -> {
            if (MyApplication.needTicket){
                List<HttpParaBean> para=new ArrayList<>();
                para.add(new HttpParaBean("token","token"));
                Network.post(para, "wbhMain/getTickets", new Callback() {
                    @SuppressLint("StringFormatMatches")
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        runOnUiThread(() -> {
                            try {
                                JSONObject jo = new JSONObject(response.body().string());
                                if (jo.getInt("code")==1){
                                    if (jo.getJSONArray("datalist").getJSONObject(0).getInt("ticket")>0){
                                        Tools.showDialog(MyPostActivity.this,
                                                String.format(getResources().getString(R.string.restTicket), jo.getJSONArray("datalist").getJSONObject(0).getInt("ticket")),
                                                String.format(getResources().getString(R.string.dialog_content_post), "1"),
                                                getResources().getString(R.string.cancel), (o, dialog) -> dialog.dismiss(), getResources().getString(R.string.confirm), (o, dialog) -> {
                                                    dialog.dismiss();
                                                    flashTime(position);
                                                });
                                    }else {
                                        Tools.showDialog(MyPostActivity.this,
                                                String.format(getResources().getString(R.string.restTicket), jo.getJSONArray("datalist").getJSONObject(0).getInt("ticket")),
                                                getResources().getString(R.string.ticketNotEnough),
                                                getResources().getString(R.string.watching),
                                                (o, dialog) -> { dialog.dismiss();
                                                /*
                                                看完后给三张扣除1张，
                                                 */
                                                    flashTime(position);
                                                }, getResources().getString(R.string.cancel), (o, dialog) -> {
                                                    dialog.dismiss();
                                                });
                                    }
                                }else {
                                    Tools.toast( getResources().getString(R.string.getTicketFaild));
                                }
                            } catch (JSONException | IOException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                });
            }else {
                Tools.showDialog(MyPostActivity.this, getResources().getString(R.string.tips),
                        getResources().getString(R.string.refreshContent),
                        getResources().getString(R.string.confirm),
                        (o, dialog) -> { dialog.dismiss();
                            flashTime(position);
                        }, getResources().getString(R.string.cancel), (o, dialog) -> {
                            dialog.dismiss();
                        });
            }
        }, (v, position) -> {
        });
        binding.myPostList.setAdapter(adp);
        binding.myPostRefresh.setRefreshHeader(new ClassicsHeader(this));
        binding.myPostRefresh.setRefreshFooter(new ClassicsFooter(this));
        binding.myPostRefresh.setOnRefreshListener(refreshLayout -> {
            current=1;refresh(refreshLayout,null);
        });
        binding.myPostRefresh.setOnLoadMoreListener(refreshLayout -> refresh(null,refreshLayout));
        binding.myPostTab.addTab( binding.myPostTab.newTab().setText(getResources().getString(R.string.normalArticle)));
        binding.myPostTab.addTab( binding.myPostTab.newTab().setText(getResources().getString(R.string.frozenArticle)));
        binding.myPostTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                nowPos=tab.getPosition();
                current=1;
                refresh(null,null);
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }
            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
        binding.myPostList.setOnItemClickListener((adapterView, view, i, l) -> {
            MyApplication.postBean=data.get(i);
            startActivity(new Intent(MyPostActivity.this,PostDetailActivity.class));
        });
        refresh(null,null);
    }
    private void flashTime(int position) {
        HomeListBean bean = data.get(position);
        List<HttpParaBean> para = new ArrayList<>();
        para.add(new HttpParaBean("token", "token"));
        para.add(new HttpParaBean("bpId", bean.id));
        Network.post(para, "wbhMain/flashTime", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                runOnUiThread(()->{
                    try {
                        Tools.toast( new JSONObject(response.body().string()).getString("datalist"));
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    current=1;
                    refresh(null, null);
                });
            }
        });
    }
    private void refresh(RefreshLayout refreshLayout, RefreshLayout loadmorelayout) {
        if (loadmorelayout!=null&&refreshLayout==null) current++;
        ArrayList<HttpParaBean> list=new ArrayList<>();
        list.add(new HttpParaBean("current",String.valueOf(current)));
        list.add(new HttpParaBean("size", "5"));
        list.add(new HttpParaBean("token", "token"));
        list.add(new HttpParaBean("language","0"));
        String url="";
        if (nowPos==0){
            url="wbhMain/myPublish";
        }else {
            url="wbhMain/myBannedPublish";
        }
        Network.post(list, url, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                runOnUiThread(() -> {
                    try {
                        JSONObject jo1=new JSONObject(response.body().string());
                        JSONArray ja = jo1.getJSONArray("datalist");
                        if (loadmorelayout==null) data.clear();
                        if (ja.length()!=0){
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject jo = ja.getJSONObject(i);

                                JSONArray jo_imgs = jo.getJSONArray("imgs");
                                String img_url="";
                                if (jo_imgs.length()>0) img_url= jo_imgs.getString(0);
                                int type=1;
                                if (nowPos==1)
                                    type=3;
                                String bannedCount = "0";
                                if (jo.has("bannedCount")) bannedCount=jo.getString("bannedCount");
                                data.add( new HomeListBean(type,jo.getString("bp_content"), img_url, jo.getString("bp_report"), jo.getString("bp_sort"), jo.getString("bp_title"), jo.getString("bp_type"), jo.getInt("bu_id"), jo.getString("id"), jo.getInt("bp_click_number"), jo.getString("time"), jo.getString("wb_nickname"), jo.getString("wb_url"),bannedCount,null));
                            }
                        }
                        adp.notifyDataSetChanged();
                        if (refreshLayout!=null)refreshLayout.finishRefresh(0);
                        if (loadmorelayout!=null)loadmorelayout.finishLoadMore(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
}